package com.sdy.mvc.utils;


import com.sdy.common.constant.Constants;
import com.sdy.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * Created by zzq on 2017/8/24.
 */
@Slf4j
public class HttpUtil {

    public static String getIpAddr(HttpServletRequest req) {
        String ip = req.getHeader("X-Forwarded-For");

        try {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = req.getHeader("x-forwarded-for");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = req.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = req.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = req.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = req.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = req.getRemoteAddr();
            }
        } finally {
            String tmp1 = StringUtil.substringBefore(ip, ",");
            long cnt = tmp1.chars().filter(c -> c == ':').count();
            if (cnt == 1) {
                ip = StringUtil.substringBefore(tmp1, ":");
            } else {
                ip = tmp1;
            }
        }
        return ip;
    }

    /**
     * 获取本机IP地址
     */
    public static String getLocalIpAddress() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()){
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                if (!netInterface.isLoopback() && !netInterface.isVirtual() && netInterface.isUp()) {
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress ip = addresses.nextElement();
                        if (ip instanceof Inet4Address
                                && !ip.isLoopbackAddress() //loopback地址即本机地址，IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
                                && !ip.getHostAddress().contains(":")) {
                            return ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (Exception e){
            log.error("Get local ip failed!", e);
        }
        return null;
    }

    public static Integer getUserId(HttpServletRequest request) {
        return (Integer) request.getSession().getAttribute(Constants.SESSION_USER_ID);
    }

    public static Integer getUserId(HttpServletRequest request, String sessionKey) {
        return (Integer) request.getSession().getAttribute(sessionKey);
    }
    
    public static boolean checkhost(String host1, String host2) {
        if (host1 == null || host2 == null) {
            return false;
        }
        return updateHostFormat(host1).equals(updateHostFormat(host2));
    }
    
    private static String updateHostFormat(String host) {
        if (host.startsWith("https://")) {
            host = host.substring(8);
            int endIdx = host.indexOf("/");
            endIdx = endIdx < 0 ? host.length() : endIdx;
            host = host.substring(0, endIdx);
            if (!host.contains(":")) {
                host = host.concat(":443");
            }
        }
        if (host.startsWith("http://")) {
            host = host.substring(7);
            int endIdx = host.indexOf("/");
            endIdx = endIdx < 0 ? host.length() : endIdx;
            host = host.substring(0, endIdx);
            if (!host.contains(":")) {
                host = host.concat(":80");
            }
        }
        return host;
    }
    
    public static String getUserToken(HttpServletRequest request) {
        // 优先取url中的token，其次取cookie中的token
        String token = (String) request.getAttribute("token");
        if (token == null) {
            token = request.getParameter("token");
        }
        if (token == null) {
            token = CookieUtil.getCookie(request, "token");
        }
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return token;
    }
    
    public static String appendUrlParam(String url, String key, String value) {
        if (url == null) {
            return null;
        }
        if (url.indexOf('?') >= 0) {
            return url.concat("&").concat(key).concat("=").concat(value);
        } else {
            return url.concat("?").concat(key).concat("=").concat(value);
        }
    }

    public static String removeUrlParam(String url, String key) {
        if (url == null) {
            return null;
        }
        url = url.replaceAll("\\?" + key + "=[^=?&/]+", "?rm=1");
        url = url.replaceAll("&" + key + "=[^=?&/]+", "");
        return url;
    }

    public static HttpSession getSession(HttpServletRequest request) {
        return request.getSession();
    }

    public static void main(String[] args) {
        System.out.println(updateHostFormat("http://192.168.1.132:6666/eq/rrr?ewq$1"));
    }
}
